package mycache

import (
	"devops-super/internal/consts"
	"devops-super/internal/model/mymodel"
	"devops-super/internal/service"
	"github.com/gogf/gf/v2/database/gredis"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcache"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/util/gconv"
)

type sMycache struct{}

func init() {
	service.RegisterMycache(New())
}

func New() *sMycache {
	return &sMycache{}
}

func (s *sMycache) Init() {}

func (s *sMycache) CacheSetAdapter() {
	var (
		err   error
		ctx   = gctx.New()
		cache = gcache.New()
	)
	confKey := consts.EnvConfig_cache + ".default"
	confString, err := g.Cfg().Get(ctx, confKey)
	if err != nil {
		panic(err)
	}
	if confString.String() == "redis" {
		confKeyRedis := consts.EnvConfig_cache + ".redis"
		confStringRedis, err := g.Cfg().Get(ctx, confKeyRedis)
		if err != nil {
			panic(err)
		}
		var conf *mymodel.MyRedis
		err = gconv.Structs(confStringRedis, &conf)
		if err != nil {
			panic(err)
		}

		minIdle := 4
		if conf.MinIdle > minIdle {
			minIdle = conf.MinIdle
		}
		maxIdle := 8
		if conf.MaxIdle > maxIdle {
			maxIdle = conf.MaxIdle
		}
		maxActive := 10
		if conf.MaxActive > maxActive {
			maxActive = conf.MaxActive
		}
		redisConfig := &gredis.Config{
			Address:   conf.Addr,
			Pass:      conf.Pass,
			Db:        conf.DB,
			MaxIdle:   maxIdle,
			MaxActive: maxActive,
			MinIdle:   minIdle,
		}
		redis, err := gredis.New(redisConfig)
		if err != nil {
			panic(err)
		}
		cache.SetAdapter(gcache.NewAdapterRedis(redis))
		glog.Line().Info(ctx, "redis config:", gconv.String(confStringRedis))
	}
	service.SetCacheInstance(cache)
}
